// 加载中提示
var loader = "<div class='loading' style='margin:0 auto;text-align:center; padding-top:20px;'><img src='/cwp/src/assets/img/loading/cmcc_loading_lg.gif' style='height:35px;width:35px;display:inline;' alt=''/><p style='font-size:12px;display:block;margin-top: 10px'>载入中，请稍候...</p></div>";

//树形节点点击添加
var countTreeId;
$(function(){
    initBuildingTree();
});

//验证
$(document).ready(function () {
    $.formValidator.initConfig({
        formid: "frmMain", onerror: function (msg) {return false;}, onsuccess: function () {return true;}
    });
    $("#regionCode").formValidator({
        onfocus: "请输入空间编码",
        oncorrect: " "
    }).InputValidator({
        min: 1,
        max: 100,
        onempty: "请输入空间编码",
        onerror: "请输入空间编码"
    });
    $("#regionName").formValidator({
        onfocus: "请输入空间名称",
        oncorrect: " "
    }).InputValidator({
        min: 1,
        max: 100,
        onempty: "请输入空间名称",
        onerror: "请输入空间名称"
    });

});

//获取列表部门树数据
function initBuildingTree(){
	$("#treeOrg").html(loader);
	$("#regionId").val("");

    $.getJSON('/cwp/src/json/region/region004.json',function(data){
        successResultBuilding(data);
    })

    // PostForm("/cwp/front/sh/region!execute", "uid=region004x", "", successResultBuilding, '',"frmTree");
}

function successResultBuilding(result){
    switch (result.returnCode) {
        case "0":
            $("#dataTreeTotal").text( "共"+ result.beans.length +"条记录");
            if(result.beans.length>0) {
                constructTree(result.beans);
            }
            break;
        case "1":
            tipModal("icon-cross", "空间树获取失败");
            break;
        case "-9999":
            tipModal("icon-cross", "空间树获取失败");
            break;
        default:
            break;
    }
}

//空间类型选择
$("#buildingType").on("change",function(){
    if($(this).val() == "0"){
        $("#parentText").val("");
        $("#parentId").val("");
        $(".pnode").hide();
    }
    else{
        $(".pnode").show();
    }
});

//1、判断空间类型为区域
//2、根据父ID归类
//3、
//重构树对象数据
function constructTree(data){
    var zNodes=[];
    for(var i=0; i<data.length; i++){
        var obj = new Object();
        obj.id=data[i].regionId;
        obj.pId=data[i].parentId;
        obj.name=data[i].regionName;
        obj.code=data[i].regionCode;
        obj.type=data[i].regionType;
        obj.state=data[i].regionState;
        zNodes.push(obj);
    }

    var setting = {
        view: {
            showIcon: false,
            selectedMulti: false,
            addDiyDom:addDiyDom
        },
        data: {
            simpleData: {
                enable: true
            }
        }
    };
    $.fn.zTree.init($("#treeOrg"), setting, zNodes);
    var zTree = $.fn.zTree.getZTreeObj("treeOrg");
    if(countTreeId!=undefined && countTreeId!=""){
        var getTreeNode=zTree.getNodeByTId(countTreeId);
        //默认选中节点
        zTree.selectNode(getTreeNode);
        //默认展开节点
        zTree.expandNode(getTreeNode,true);
    }
    //添加表头
    var li_head=' <li class="head"><a><div class="diy">空间名称</div><div class="diy">空间编码</div><div class="diy">空间类型</div>' +
        '<div class="diy">操作</div></a></li>';
    var rows = $("#treeOrg").find('li');
    if(rows.length>0){
        rows.eq(0).before(li_head)
        $("#dataTreeData").remove();
    }else{
        $("#treeOrg").append(li_head);
        $("#treeOrg").append('<li><td style="text-align: center;line-height: 30px;" >无符合条件数据</li>')
    }
}
;

//新增保存
$("#btn_saveUser").on("click",function(){
    //判断表单验证是否通过
	$("#regionType").formValidator({
        onfocus:"请选择空间类型",
        oncorrect:"&nbsp;"
    }).InputValidator({
        min:1,
        onempty:"请选择空间类型",
        onerror:"请选择空间类型"
    });
    if($.formValidator.PageIsValid()){
        var buildingId=$("#hidRegionId").val();
        if(buildingId==""){
            PostForm("/cwp/front/sh/region!execute", "uid=region005x", "post", successResultSaveBuilding, '',"frmMain");
        }
        else{
            PostForm("/cwp/front/sh/region!execute", "uid=region002x", "post", successResultEditBuilding, '',"frmMain");
        }
    }
});

//新增请求成功回调函数
function successResultSaveBuilding(result) {
    switch (result.returnCode) {
        case "0":
            $("#modalDistrict").modal("hide");
            tipModal("icon-checkmark", "保存成功");
            initBuildingTree();
            break;
        case "1":
            tipModal("icon-cross", result.returnMessage);
            break;
        case "-9999":
            tipModal("icon-cross", "保存失败");
            break;
        default:
            break;
    }
}

//编辑空间信息回调
function successResultEditBuilding(result){
    switch (result.returnCode) {
        case "0":
            $("#modalDistrict").modal("hide");
            tipModal("icon-checkmark", "保存成功");
            initBuildingTree();
            break;
        case "1":
            tipModal("icon-cross", result.returnMessage);
            break;
        case "-9999":
            tipModal("icon-cross", "保存失败");
            break;
        default:
            break;
    }
}

function beforeRemove(id) {
    $("#regionId").val(id.getAttribute("data-id"));
    $("#modalDelBuilding").modal({//启用modal ID
        keyboard: true,
        backdrop: 'static'
    }).on('show.bs.modal', centerModal());
    $(window).on('resize', centerModal());
    return false;
}

//删除节点
$("#btnDelete").on("click",function(){
    PostForm("/cwp/front/sh/region!execute", "uid=region003x", "", delBuildingbyId, "","frmTree");
});
function delBuildingbyId(result){
    $("#modalDelBuilding").modal("hide");
    switch (result.returnCode) {
        case "0":
            tipModal("icon-checkmark", "删除成功");
            initBuildingTree();
            break;
        case "1":
            tipModal("icon-cross", result.returnMessage);
            break;
        case "-9999":
            tipModal("icon-cross", "删除失败");
            break;
        default:
            break;
    }
}

//编辑
function beforeEditName(id) {
	updateDeptTreeModal(id.getAttribute("data-id"));
    // setTimeout(function() {
    //     $("#regionId").val(id.getAttribute("data-id"));
    //     PostForm("/cwp/front/sh/region!execute", "uid=region001x", "", getBuildingById, '',"frmTree");
    // }, 0);
    return false;
}

//显示空间详情
function getBuildingById(result){
    modalDistrict();
    $("#modalDistrict .modal-title").html("编辑空间");
    switch (result.returnCode) {
        case "0":
        	$("#hidRegionId").val(result.object.regionId);
            $("#parentId").val(result.object.parentId);
            if(result.object.parentId != 0){
                $("#parentText").val(result.object.parentRegionName);
            }else{
                $("#parentText").val("")
            }
            $("#regionCode").val(result.object.regionCode);
            $("#regionName").val(result.object.regionName);
            $("#regionType").val(result.object.regionType);
            $("#regionArea").val(result.object.regionArea);
            $("#regionHeigh").val(result.object.regionHeigh);
            $("#regionState").val(result.object.regionState);
            $("#regionDescription").val(result.object.regionDescription);
            //add
            $("#openingTime").val(result.object.openingTime);
            $("#closeTime").val(result.object.closeTime);
            $("#ratedPowerConsumption").val(result.object.ratedPowerConsumption);
            $("#remark").val(result.object.remark);
            //addEnd
            break;
        case "1":
            tipModal("icon-cross", result.returnMessage);
            break;
        case "-9999":
            tipModal("icon-cross", "获取详情失败");
            break;
        default:
            break;
    }
}

//打开模态框
function modalDistrict(){
    //$("#modalAddDistrict").html(modal);
    $(".tipArea div").html("").attr("class","");
    $("#modalDistrict .modal-title").html("新增空间");
    $("#hidRegionId").val("");
    $("#parentText").val("");
    $("#parentId").val("");
    $("#regionCode").val("");
    $("#regionName").val("");
    $("#regionType").val("");
    $("#regionArea").val("");
    $("#regionHeigh").val("");
    $("#regionState").val("");
    $("#regionDescription").val("");
    //add
    $("#openingTime").val("");
    $("#closeTime").val("");
    $("#ratedPowerConsumption").val("");
    $("#remark").val("");
    //addEnd
    $("#modalDistrict").modal({
        keyboard: true,
        backdrop: 'static'
    }).on('show.bs.modal', centerModal());
    $(window).on('resize', centerModal());
}

//点击节点事件
function beforeClick(treeId, treeNode){
    var buildingId=treeNode.id;
    $("#buildingId").val(buildingId);
    isFirst=true;
    //searchUserList(1);
}

//新增
$('#btnAddBuilding').on("click",function(){
    modalDistrict();
    addDeptTreeModal();
});

//自定义DOM节点
function addDiyDom(treeId, treeNode) {
    countTreeId = treeNode.tId;
    var spaceWidth = 15;
    var liObj = $("#" + treeNode.tId);
    var aObj = $("#" + treeNode.tId + "_a");
    var switchObj = $("#" + treeNode.tId + "_switch");
    var icoObj = $("#" + treeNode.tId + "_ico");
    var spanObj = $("#" + treeNode.tId + "_span");
    aObj.attr('title','');
    aObj.append('<div class="diy swich"></div>');
    var div = $(liObj).find('div').eq(0);
    switchObj.remove();
    spanObj.remove();
    icoObj.remove();
    div.append(switchObj);
    div.append(spanObj);
    $("#" + treeNode.tId + "_span").text(treeNode.buildingDesc);
    var spaceStr = "<span style='height:1px;display: inline-block;width:" + (spaceWidth * treeNode.level) + "px'></span>";
    switchObj.before(spaceStr);
    var editStr = '';
    editStr += '<div class="diy">' + (treeNode.code )+ '</div>';
    editStr += '<div class="diy">' + (treeNode.type )+ '</div>';
    editStr += '<div class="diy"><a class="t-btn t-btn-sm t-btn-red t-btn-deal btnDelete tree-btnred" onclick="beforeRemove(this)" data-tid="'+ treeNode.tId +'"   data-id="'+ treeNode.id +'">删除</a><a class="t-btn t-btn-sm t-btn-blue t-btn-deal editDictData tree-btnblue" onclick="beforeEditName(this)"  data-tid="'+ treeNode.tId +'"   data-id="'+ treeNode.id +'" >编辑</a></div>';
    aObj.append(editStr);
    $("#" + treeNode.tId + "_a").on("click",function(){
        $("#parentId").val(treeNode.id);
    })
}

//新增初始化部门数
function updateDeptTreeModal(id){
	$("#regionId").val(id);
    // PostForm("/cwp/front/sh/region!execute", "uid=region004x", "", getDeptTreeModal, '',"frmTree");
    modalDistrict();

}

//新增初始化部门数
function addDeptTreeModal(){
	$("#regionId").val("");
    PostForm("/cwp/front/sh/region!execute", "uid=region004x", "", getDeptTreeModal, '',"frmTree");

}

//获取数据初始化部门树
function getDeptTreeModal(result){
    var zNodes=[];
    for(var i=0; i<result.beans.length; i++){
        var obj = new Object();
        obj.id=result.beans[i].regionId;
        obj.pId=result.beans[i].parentId;
        obj.name=result.beans[i].regionName;
        zNodes.push(obj);
    }
    if(result.returnCode=="0"){
        //配置组织结构树
        var setting = {
            view: {
                dblClickExpand: false,
                showIcon: false,                 //隐藏节点图标
                selectedMulti: false             //设置是否允许同时选中多个节点
            },
            data: {
                simpleData: {
                    enable: true
                }
            },
            callback: {
                beforeClick: beforeClickSelect
            }
        };

        $.fn.zTree.init($("#treeOrgModal"), setting, zNodes);
        var zTree = $.fn.zTree.getZTreeObj("treeOrgModal");
        if(countTreeId!=undefined && countTreeId!=""){
            var getTreeNode=zTree.getNodeByTId(countTreeId);
            //默认选中节点
            zTree.selectNode(getTreeNode);
            //默认展开节点
            zTree.expandNode(getTreeNode,true);
        }
    }
}

//渲染新增部门树
function beforeClickSelect(treeId, treeNode) {
    // var zTree = $.fn.zTree.getZTreeObj("treeOrgModal");
    $("#parentText").val(treeNode.name);
    $("#parentText").blur();
    $("#parentId").val(treeNode.id);
    hideMenu();
    return false;
}

$("#parentText").on("focus",function(){
    showMenu();
});

//显示部门树
function showMenu() {
    var deptIdObj = $("#parentText");
    var deptIdOffset = $("#parentText").offset();
    //$("#menuContent").slideDown("fast");
    $("#menuContent").css({left:deptIdOffset.left + "px", top:deptIdOffset.top + deptIdObj.outerHeight() + "px"}).slideDown("fast");
    $("body").bind("mousedown", onBodyDown);
}

//隐藏部门树
function hideMenu() {
    $("#menuContent").fadeOut("fast");
    $("body").unbind("mousedown", onBodyDown);
}

function onBodyDown(event) {
    if (!(event.target.id == "parentText" || event.target.id == "menuContent" || $(event.target).parents("#menuContent").length>0)) {
        hideMenu();
    }
}


//初始化文件上传控件
$(function() {
    $("#file_upload").uploadify({
        height        : 28,
        swf           : '../../../assets/lib/uploadify/uploadify.swf?ver='+Math.random(),
        uploader      : '/cwp/front/sh/region!execute?uid=region006x',
        width         : 78,
        'fileTypeExts': '*.xls; *.xlsx', //文件后缀限制 默认：'*.*'
        'fileSizeLimit': '10240KB', //文件大小限制 0为无限制 默认KB
        'fileTypeDesc' : '.xls; *.xlsx文件格式',//文件类型描述
        'method': 'post', //提交方式Post 或Get 默认为Post
        'buttonText': '', //按钮文字

        'multi': false, //多文件上传
        'fileObjName': 'files[]', //设置一个名字，在服务器处理程序中根据该名字来取上传文件的数据。默认为Filedata
        'queueID': 'I am dont need',  //默认队列ID
        'removeCompleted': true, //上传成功后的文件，是否在队列中自动删除
        'overrideEvents': ['onDialogClose', 'onSelectError','onUploadStart', 'onUploadSuccess', 'onUploadError'],//重写事件
        //返回一个错误，选择文件的时候触发          
        'onSelectError': function (file, errorCode, errorMsg) {
            var msgText = "";
            switch (errorCode) {
                case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
                    //this.queueData.errorMsg = "每次最多上传 " + this.settings.queueSizeLimit + "个文件";
                    msgText += "每次最多上传 " + this.settings.queueSizeLimit + "个文件";
                    break;
                case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
                    msgText += "文件大小超过限制" + this.settings.fileSizeLimit + "";
                    break;
                case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
                    msgText += "文件大小为0";
                    break;
                case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
                    msgText += "文件格式不正确，仅限 " + this.settings.fileTypeExts;
                    break;
                default:
                    msgText += "错误代码：" + errorCode + "\n" + errorMsg;
            }
            tipModal('icon-cross',msgText);
        },
        // 文件开始上传时回调函数
        'onUploadStart': function (file) {
            //显示上传状态
            $("#uploadTip").text("正在上传...").attr("class","t-loading-cmcc");
        },

        //检测FLASH失败调用
        'onFallback': function () {
            tipModal("icon-cross", "您未安装FLASH控件，无法上传图片！请安装FLASH控件后再试。");
        },

        //文件上传成功后的回掉方法
        'onUploadSuccess': function (file, data, response) {
            var data=JSON.parse(data)
            if(data.returnCode == '0'){
                //刷新列表数据
                initBuildingTree();
                tipModal('icon-checkmark','导入完成');
            }
            else if(data.returnCode == '-9999'){
                tipModal('icon-cross','导入失败');
            }
            else{
                tipModal('icon-cross',data.returnMessage);
            }
            $("#uploadTip").text("批量导入").attr("class","t-btn t-btn-blue");
        },

        //文件上传出错时触发，参数由服务端程序返回。
        'onUploadError': function (file, errorCode, errorMsg, errorString) {
            tipModal('icon-cross',"上传出现异常，请重新上传");
        }
    });
});